/**
*	AssetLoader
*	@author 	Liam O'Donnell 2007-11-18
**/

package com.spikything.utils {
	
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import com.spikything.utils.events.AssetLoaderEvent;

	public class AssetLoader extends Sprite {
		
		private var _percentLoaded	:Number;
		private var _loader 		:Loader;
		private var _target 		:Sprite;
		private var _url 			:String;
	
		public function AssetLoader (url:String = null, target:Sprite = null, px:Number = 0, py:Number = 0) {
			if (url) loadAsset(url, target, px, py);
		}
		
		public function loadAsset (url:String, target:Sprite, px:Number = 0, py:Number = 0):Sprite {
			_url = url;
			_loader = new Loader();
			var request:URLRequest = new URLRequest(url);
			_target = target;
			_target.addChild(_loader);
			_loader.load(request);
			_loader.x = px;
			_loader.y = py;
			_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			return _loader.content as Sprite;
		}
		
		public function kill ():void {
			_loader.unload();
		}
		
		private function errorHandler(e:IOErrorEvent):void {
			dispatchEvent(new AssetLoaderEvent(AssetLoaderEvent.ERROR, null));
		}
		
		public function get id ():String {
			return _url;
		}
		
		public function get percentLoaded ():Number {
			return _percentLoaded;
		}
		
		public function get content ():Sprite {
			return _loader.content as Sprite;
		}
		
		public function get loader ():Loader {
			return _loader;
		}

		public function get target ():Sprite {
			return _target as Sprite;
		}
		
		public function get assetURL ():String {
			return _url;
		}
		
		protected function loadProgress (event:ProgressEvent):void {
			_percentLoaded = Math.round(event.bytesLoaded/event.bytesTotal * 100);
		}
		
		protected function completeHandler (e:Event):void {
			dispatchEvent(new AssetLoaderEvent(AssetLoaderEvent.LOADED, _loader.content as MovieClip));
		}
	
	}

}